import wordcloud
import pymysql
import matplotlib.pyplot as plt
import re

from PIL import Image
import numpy as np

conn = pymysql.connect(host='gsy-cloud', user='root', password='rootQWE', database='python', port=32769)
cursor = conn.cursor()
query_sql = "select thumbs_up_num,thumbs_down_num,comment,comment_phrase from tb_rate_comment where pro_pk_id = '%s'"


def load_stop():
    stop_set = set()
    with open('../stop.txt', 'r') as f:
        lines = f.readlines()
        for line in lines:
            stop_set.add(line.strip().lower())
    # print(stop_set)
    return stop_set


def load_and_print(pk_id, stop_set: set):
    cursor.execute(query_sql % str(pk_id))
    rows = cursor.fetchall()
    word_map = dict()
    text = ''
    for row in rows:
        thumbs_up_num = int(row[0])
        thumbs_down_num = int(row[1])
        comment = str(row[2])
        comment = re.split(r'\s+', re.sub(re.compile(r"[.\"0-9,=%\-()]"), " ", comment))
        for i in comment:
            i = i.lower()
            if i.lower().replace(".", "") in stop_set:
                continue
            try:
                word_map[i] += 1
            except:
                word_map[i] = 1
        plus_num = len(comment) * 0.1
        comment_phrase = str(row[3])
        comment_phrase = comment_phrase.split("$$")
        for i in comment_phrase:
            if i.lower().replace(".", "") in stop_set:
                continue
            try:
                word_map[i] += plus_num
            except:
                word_map[i] = plus_num
        if (thumbs_up_num - thumbs_down_num) > 0:
            times = thumbs_up_num - thumbs_down_num
            for i in word_map:
                word_map[i] = word_map[i] + word_map[i] * times * 0.3

    query_name_sql = "SELECT pro_first_name,pro_last_name FROM tb_teacher WHERE pro_pk_id = '%s';"
    cursor.execute(query_name_sql % str(pk_id))
    row = cursor.fetchone()
    name = row[0] + ' ' + row[1]
    aimask = np.array(Image.open("cloud.png"))
    ww = wordcloud.WordCloud(background_color='white', contour_width=1 , repeat=True, mask=aimask)
    ww.generate_from_frequencies(word_map)
    ww.to_file('../pic/' + name + '.png')

    plt.imshow(ww)  # 使用plt库显示图片
    plt.axis("off")
    plt.show()


if __name__ == "__main__":
    stop_set = load_stop()
    # load_and_print(1744964, stop_set,"Mustafa Bilgic.png")
    # load_and_print(125289, stop_set,"Michael Lee.png")
    # load_and_print(1848014, stop_set, "papademas.png")
    # load_and_print(131974, stop_set, "virgil.png")
    # load_and_print(2347602, stop_set, "yousef.png")
    # load_and_print(1432624, stop_set, "Joohee.png")
    # load_and_print(1956102, stop_set)
    # load_and_print(2328269, stop_set)
    # load_and_print(1605816, stop_set)
    # load_and_print(2142964, stop_set)
    # load_and_print(2412885, stop_set)
    load_and_print(600610, stop_set)
    # load_and_print(2388641, stop_set)
